<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="餐别" prop="mealTypes">
        <el-checkbox-group v-model="formData.mealTypes">
          <el-checkbox
            v-for="dict in getStrDictOptions(DICT_TYPE.SCHOOL_MEAL_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="x"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="disabledDate"
          @change="onDateRangeChange"
          @calendar-change="onCalendarChange"
          @visible-change="onVisibleChange"
          class="w-full"
        />
      </el-form-item>
      <el-form-item label="地域" prop="area">
        <el-radio-group v-model="formData.area">
          <el-radio label="north">北方</el-radio>
          <el-radio label="south">南方</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="节气" prop="solarTerms">
        <el-switch v-model="formData.solarTerms" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RecipeMenusWeeklyApi, RecipeMenusWeekly } from '@/api/school/recipe/menusWeekly'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'

// 扩展 dayjs 功能
dayjs.extend(isoWeek)
dayjs.extend(isSameOrAfter)

/** 周食谱 表单 */
defineOptions({ name: 'RecipeMenusWeeklyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter() // 路由

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const dateRange = ref<[number, number] | []>([]) // 日期范围
const tempRange = ref<[Date, Date] | []>([]) // 临时日期范围，用于calendar-change事件
const formData = ref({
  menuId: undefined,
  mealTypes: [] as string[],
  weekStartDate: undefined,
  weekEndDate: undefined,
  area: 'north',
  solarTerms: false,
  remark: undefined,
  dateRange: [] as number[] // 添加dateRange字段用于表单校验
})
const formRules = reactive({
  mealTypes: [{ required: true, message: '餐别不能为空', trigger: 'blur' }],
  dateRange: [{ required: true, message: '日期范围不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 禁用跨周选择和过去周选择
const disabledDate = (date: Date) => {
  const today = dayjs().startOf('day')

  // 禁用过去的日期（今天之前的日期）
  if (dayjs(date).isBefore(today, 'day')) {
    return true
  }

  // 如果没有选择开始日期，则不限制跨周选择
  if (!tempRange.value || !tempRange.value[0]) {
    // 但仍然禁用过去的周
    const dateWeekStart = dayjs(date).isoWeekday(1).startOf('day') // 当前日期所在周的周一
    return dateWeekStart.isBefore(today.isoWeekday(1).startOf('day'), 'day')
  }

  // 获取选择的开始日期所在周
  const selectedDate = dayjs(tempRange.value[0])
  const selectedWeekStart = selectedDate.isoWeekday(1).startOf('day') // 选择日期所在周的周一
  const selectedWeekEnd = selectedDate.isoWeekday(7).startOf('day') // 选择日期所在周的周日

  // 禁用不在本周的日期
  return (
    dayjs(date).isBefore(selectedWeekStart, 'day') || dayjs(date).isAfter(selectedWeekEnd, 'day')
  )
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await RecipeMenusWeeklyApi.getRecipeMenusWeekly(id)
      formData.value = {
        ...data,
        dateRange:
          data.weekStartDate && data.weekEndDate ? [data.weekStartDate, data.weekEndDate] : [] // 初始化dateRange
      }

      // 设置日期范围
      if (data.weekStartDate && data.weekEndDate) {
        dateRange.value = [data.weekStartDate, data.weekEndDate]
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时，默认设置为当前周或下周的周一至周五
    const now = dayjs()
    let monday = now.isoWeekday(1).startOf('day') // 本周一
    let friday = monday.add(4, 'day').startOf('day') // 本周五

    // 如果当前周的周五已经过去，则默认选择下周
    if (friday.isBefore(now, 'day')) {
      monday = monday.add(1, 'week') // 下周一
      friday = friday.add(1, 'week') // 下周五
    }

    dateRange.value = [monday.valueOf(), friday.valueOf()]
    formData.value.dateRange = [monday.valueOf(), friday.valueOf()] // 同步设置dateRange
    formData.value.weekStartDate = monday.valueOf()
    formData.value.weekEndDate = friday.valueOf()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 日历变化处理 */
const onCalendarChange = (val: [Date, Date] | []) => {
  tempRange.value = val
}

/** 日期范围变化处理 */
const onDateRangeChange = (val: [number, number] | []) => {
  if (val && val.length === 2) {
    // 确保开始日期是周一，结束日期是周日
    const startDate = dayjs(val[0])
    const monday = startDate.isoWeekday(1).startOf('day') // 本周一
    const sunday = monday.isoWeekday(7).startOf('day') // 本周日

    // 如果选择的日期不在同一周内，则调整为完整的一周
    if (dayjs(val[1]).isAfter(sunday) || dayjs(val[1]).isBefore(monday)) {
      // 如果结束日期超出本周范围，则设置为本周日
      dateRange.value = [monday.valueOf(), sunday.valueOf()]
      formData.value.dateRange = [monday.valueOf(), sunday.valueOf()] // 同步更新dateRange
      formData.value.weekStartDate = monday.valueOf()
      formData.value.weekEndDate = sunday.valueOf()
    } else {
      formData.value.dateRange = val // 同步更新dateRange
      formData.value.weekStartDate = val[0]
      formData.value.weekEndDate = val[1]
    }
  } else {
    // 清空时重置限制
    formData.value.dateRange = [] // 清空dateRange
    formData.value.weekStartDate = undefined
    formData.value.weekEndDate = undefined
    tempRange.value = []
  }
}

/** 日期选择器可见性变化处理 */
const onVisibleChange = (visibility: boolean) => {
  // 当日期选择器隐藏时，重置临时范围限制
  if (!visibility) {
    tempRange.value = []
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      mealTypes: formData.value.mealTypes.join(',')
    }
    if (formType.value === 'create') {
      const menuId = await RecipeMenusWeeklyApi.createRecipeMenusWeekly(data)
      message.success(t('common.createSuccess'))
      // 跳转到周食谱详情页面
      await router.push({
        name: 'WeeklyRecipe',
        query: { menuId }
      })
      dialogVisible.value = false
    } else {
      await RecipeMenusWeeklyApi.updateRecipeMenusWeekly(data as unknown as RecipeMenusWeekly)
      message.success(t('common.updateSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    menuId: undefined,
    mealTypes: [] as string[],
    weekStartDate: undefined,
    weekEndDate: undefined,
    area: 'north',
    solarTerms: false,
    remark: undefined,
    dateRange: [] // 重置dateRange
  }
  dateRange.value = []
  tempRange.value = []
  formRef.value?.resetFields()
}
</script>
